/*
 * @Description: 测量
 * @Author: yech
 * @Date: 2021-09-05
 */

import { Ref, ref, watch } from 'vue';
import { readData, saveData } from './storage';
import type { StoreData } from '@/types';
import { MeasureType } from './measureType';
interface UseMonitorReturnType {
    monitorData: Ref<StoreData>;
    add: (type: MeasureType, value: number, date: string) => void;
    modify: (type: MeasureType, id: string, value: number) => void;
    remove: (type: MeasureType, id: string) => void;
    modifyUser: (value: string) => void;
}

// type MeasureType = 'glucose' | 'weight';

export interface MeasureHandlers {
    add: (type: MeasureType, value: number, date: string) => void;
    modify: (type: MeasureType, id: string, value: number) => void;
    remove: (type: MeasureType, id: string) => void;
}

export function useMonitor(glucoseValue: Ref<number>, weightValue: Ref<number>): UseMonitorReturnType {
    const monitorData = ref<StoreData>(readData());
    if (monitorData.value.glucose.length > 0) {
        glucoseValue.value = monitorData.value.glucose[monitorData.value.glucose.length - 1].value;
    }
    if (monitorData.value.weight.length > 0) {
        weightValue.value = monitorData.value.weight[monitorData.value.weight.length - 1].value;
    }

    watch(
        () => monitorData.value,
        () => {
            saveData(monitorData.value);
        },
        { deep: true }
    );

    function modifyUser(value: string) {
        monitorData.value.user = value;
    }

    function add(type: MeasureType, value: number, date: string) {
        monitorData.value[type].push({
            id: (monitorData.value[type].length + 1).toString(),
            value,
            date
        });
    }

    function modify(type: MeasureType, id: string, value: number) {
        const data = monitorData.value[type].find((data) => data.id === id);
        if (data) {
            data.value = value;
        }
    }

    function remove(type: MeasureType, id: string) {
        const index = monitorData.value[type].findIndex((data) => data.id === id);
        if (index !== -1) {
            monitorData.value[type].splice(index, 1);
        }
    }

    return {
        monitorData,
        add,
        modify,
        remove,
        modifyUser
    };
}
